<!--
/**
* @description **设备管理
* @author mingd
* @date 2020-05-14
*/
-->
<template>
  <div class="menuManagement">
    <section class="menuManagement-tree">
      <!-- 左侧树状图 -->
      <div class="tree-content">
        <a-spin :spinning="leftTreeLoading"
                wrapperClassName="tree-spin">
          <a-tree :show-line="true"
                  :selectedKeys="[currSelTreeNode.key]"
                  :show-icon="true"
                  :tree-data="menuTree"
                  @select="selectLine">
            <template slot="custom-folder" slot-scope="{ expanded }">
              <a-icon :type="expanded ? 'folder-open' : 'folder'" theme="filled"/>
            </template>
          </a-tree>
        </a-spin>
      </div>
    </section>
    <div class="index-right-box">
      <!-- 右侧查询 -->
      <a-form-model ref="searchForm"
                    class="index-search-form-model"
                    :model="searchForm"
                    layout="inline"
      >
        <a-form-model-item label="菜单名称"
                           prop="menuName">
          <a-input allowClear
                   placeholder="请输入菜单名称"
                   v-model="searchForm.menuName"></a-input>
        </a-form-model-item>
        <a-form-model-item class="top-widget-btn">
          <a-button type="primary"
                    icon="search"
                    shape="round"
                    @click="getTableData">查询</a-button>
          <a-button icon="retweet"
                    shape="round"
                    @click="reset">重置</a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 顶部控件 -->
      <section class="table-list">
        <!-- 操作按钮 -->
        <div class="table-opt-btns">
          <a-button type="primary"
                    icon="plus"
                    @click="addMenu"
                    :disabled="!currSelTreeNode.key"
          >新增</a-button>
        </div>
        <!-- 表格操作 -->
        <!-- :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}" -->
        <a-table :columns="columns"
                 :dataSource="tableData"
                 rowKey="id"
                 :customRow="tableCustomRow"
                 bordered
                 :loading="tableLoading"
                 :pagination="pagination"
                 @change="tableChange">
          <span slot="customResType"
                slot-scope="text">
            {{convertConstName(menuTypes, text) || "无"}}
          </span>
          <div slot="operation"
               slot-scope="text,record,index"
               class="tabe-button">
            <a-button size="small"
                      type="primary"
                      icon="edit"
                      @click="editMenu(text,record,index)">编辑</a-button>
            <a-button size="small"
                      type="danger"
                      icon="close"
                      @click="deleteMenu(text, record, index)">删除</a-button>
          </div>
        </a-table>
      </section>
    </div>
    <!-- 表格 -->
    <!-- 新增编辑设备 -->
    <!-- 新增编辑表格 -->
    <operate-form :operateVisible.sync="operateVisible"
                  :menuTypes="menuTypes"
                  :operateData="operateData"
                  @handleVisible="handleOperateTableVisible"></operate-form>
    <!-- 新增编辑表格 -->
  </div>
</template>
<script>
import { getDictData } from '@/request/api/common'
import { getHnResourceList, getPageHnResource, deleteByPrimaryKey } from '@//request/api/permissionManagement/menuManagement'
import { convertConstName } from '@/utils/filter'
import { getFinalPageNo, getCustomIconTreeData } from '@/utils/index'
import {
  FormModel,
  Tree,
  Input,
  Button,
  Table,
  Spin,
  Icon
} from 'ant-design-vue'
import OperateForm from './components/OperateTable'
export default {
  name: 'menuManagement',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    AButton: Button,
    ATable: Table,
    OperateForm: OperateForm,
    ATree: Tree,
    ASpin: Spin,
    AIcon: Icon
  },
  computed: {
  },
  data () {
    return {
      // 表单
      searchForm: {
        menuName: ''
      },
      // 角色表头
      columns: [
        {
          title: '序号',
          align: 'center',
          ellipsis: true,
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '编码',
          align: 'center',
          ellipsis: true,
          dataIndex: 'code'
        },
        {
          title: '名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '路径',
          align: 'center',
          ellipsis: true,
          dataIndex: 'resValue',
          customRender: (text, record) => {
            return record.resValue || '无'
          }
        },
        {
          title: '类型',
          align: 'center',
          ellipsis: true,
          dataIndex: 'resType',
          scopedSlots: {
            customRender: 'customResType'
          }
        },
        // {
        //   title: '创建人',
        //   align: 'center',
        //   ellipsis: true,
        //   dataIndex: 'createUser'
        // },
        // {
        //   title: '创建时间',
        //   align: 'center',
        //   ellipsis: true,
        //   dataIndex: 'createTime'
        // },
        {
          title: '操作',
          align: 'center',
          ellipsis: true,
          width: 180,
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      // 表数据
      tableData: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 是否打开新增和编辑抽屉
      operateVisible: false,
      // 新增和编辑抽屉数据
      operateData: {
        type: '', // 弹出框类型
        row: {
          code: '',
          name: '',
          resValue: '',
          resType: undefined,
          sort: 1,
          parentId: ''
        }
      },
      // 当前选中树节点id
      currSelTreeNode: {},
      // 树loading
      leftTreeLoading: false,
      menuTree: [],
      // 菜单/按钮/url 数据字典
      menuTypes: [],
      // 树key
      treeKey: ''
    }
  },
  async mounted () {
    this.menuTypes = await this.getDataDictionary()
    this.getTableData()
    this.getHnResourceList()
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.operateData.row = record
            this.operateData.type = 'view'
            this.operateVisible = true
          }
        }
      }
    },
    // 检查某id下是否存在children
    checkTreeIdIsHaveChild (treeData, idValue, idKey = 'id') {
      const listData = []
      function fnc (tree) {
        tree.forEach((p) => {
          listData.push(p)
          if (p.children && (p.children.length > 0)) {
            fnc(p.children)
          }
        })
      }
      fnc(treeData)
      const target = listData.find((item) => item[idKey] === idValue)
      if (target) {
        if (target.children && target.children.length) {
          return true
        }
      }
    },
    // 获取表格菜单数据
    getTableData () {
      this.tableLoading = true
      getPageHnResource({
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: {
          name: this.searchForm.menuName,
          parentId: this.currSelTreeNode.key || ''
        }
      }).then(res => {
        this.tableLoading = false
        if (res.code === '0') {
          this.tableData = res.data.list
          this.pagination.total = res.data.total
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    selectLine (selectedKeys, info) {
      this.pagination.current = 1
      if (!selectedKeys.length) {
        this.currSelTreeNode = {}
        this.getTableData()
        return
      }
      const {
        selectedNodes
      } = info
      this.currSelTreeNode = selectedNodes[0].data.props.dataRef
      this.getTableData()
    },
    // 获取数据字典
    getDataDictionary () {
      return new Promise((resolve, reject) => {
        getDictData('Y-0B-001').then(res => {
          resolve(res.data['Y-0B-001'])
        }).catch(error => {
          reject(error)
        })
      })
    },
    convertConstName,
    // 获取树形菜单数据
    async getHnResourceList () {
      this.leftTreeLoading = true
      await getHnResourceList().then((res) => {
        if (res.code) {
          this.menuTree = getCustomIconTreeData(res.data)
          this.treeKey = new Date().getTime()
        }
      })
      this.leftTreeLoading = false
    },
    // 关闭新增和编辑抽屉
    handleOperateTableVisible (parms) {
      this.operateVisible = parms
      // 新增后重置
      if (this.operateData.type === 'add') {
        this.reset()
      } else {
        this.getTableData()
      }
      this.getHnResourceList()
    },
    reset () {
      this.pagination.current = 1
      this.searchForm = {}
      this.getTableData()
    },
    // 表格变动
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      // 查询接口
      this.getTableData()
    },
    // 新增菜单
    addMenu () {
      this.operateData.row = {
        code: '',
        name: '',
        resValue: '',
        resType: undefined,
        sort: 1,
        parentId: this.currSelTreeNode.key
      }
      this.operateData.type = 'add'
      this.operateVisible = true
    },
    // 编辑
    editMenu (text, record, index) {
      this.operateData.row = record
      this.operateData.type = 'edit'
      this.operateVisible = true
    },
    // 删除菜单
    deleteMenu (record) {
      this.$confirm({
        title: '你确定要删除此菜单?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          const isHaveChild = this.checkTreeIdIsHaveChild(this.menuTree, record.id, 'key')
          if (isHaveChild) {
            this.$message.warn('当前删除项存在子节点')
            return
          }
          deleteByPrimaryKey({
            id: record.id
          }).then(res => {
            if (res.code === '0') {
              this.$message.success('删除成功!')
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                1)
              this.getTableData()
              this.getHnResourceList()
            }
          }).catch(error => {
            console.log(error)
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.menuManagement {
  width: 100%;
  height: 100%;
  display: flex;
  .menuManagement-tree {
    width: 256px;
    background-color: #ffffff;
    margin-right: 20px;
    padding: 20px;
    box-sizing: border-box;
    .tree-content {
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .table-list {
    background-color: #ffffff;
    padding: 20px;
    box-sizing: border-box;
  }
  .tree-custom-item {
    margin-left: 10px;
  }
  .tree-spin > div > .ant-spin {
    top: 300px;
  }
}
</style>
